package com.zadtek.jpsqishi.activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zadtek.jpsqishi.R;
import com.zadtek.jpsqishi.activity.adapter.OrderoverAdapter;
import com.zadtek.jpsqishi.activity.common.Common;
import com.zadtek.jpsqishi.activity.common.Const;
import com.zadtek.jpsqishi.activity.data.OrderOverData;
import com.zadtek.jpsqishi.activity.data.OrderoverDay;
import com.zadtek.jpsqishi.frame.JsonProcessHelper;
import com.zadtek.jpsqishi.views.MyListView;
import com.zadtek.jpsqishi.views.PullDownView;
import com.zadtek.jpsqishi.views.PullDownView.OnPullDownListener;

/**
 * 已完成的订单列表
 * @author Administrator
 *
 */
public class OrderOverActivity extends BaseActivity {
	
	private ImageView backid;
	private TextView topview;
	
	private TextView ordernum;	//累计单量
	
	private PullDownView pulldownview;
	private ListView listView; 
	private OrderOverData overData;
	private OrderOverData refoverData;
	
	private ArrayList<OrderoverDay> orderoverlist;
	private ListAdapter listAdapter;
	
	private LayoutInflater inflater;
	
	private int refs = 1; // 页码
	
	private SharedPreferences sp; // 用户信息缓存
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_over);
		
		inflater = getLayoutInflater();
		backid = (ImageView) findViewById(R.id.backid);
		topview = (TextView) findViewById(R.id.topview);
		topview.setText("已完成的任务");
		backid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		ordernum = (TextView) findViewById(R.id.ordernum);
		
		pulldownview = (PullDownView) findViewById(R.id.pulldownview);
		pulldownview.enableAutoFetchMore(true, 0);
		
		listView = pulldownview.getListView();
		listAdapter = new ListAdapter();
//		listView.setDividerHeight(20);
		listView.setAdapter(listAdapter);
		
		//加载数据
		initArrays(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (!"emp".equals(msg.obj.toString())) {
					overData = (OrderOverData) msg.obj;
					ordernum.setText(overData.getTotal()+"单");
					orderoverlist = overData.getDaylist();
					listAdapter.notifyDataSetChanged();
					pulldownview.notifyDidDataLoad(false);
				} else {
					pulldownview.notifyDidDataLoad(false);
					Common.DisplayToast(OrderOverActivity.this,
							overData.getMessage(), 2);
				}
			}
		});
		
		pulldownview.setOnPullDownListener(new OnPullDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				// 刷新
				if (Common.isNetworkConnected(OrderOverActivity.this)) {
					initArrays(new Handler() {
						@Override
						public void handleMessage(Message msg) {
							if (!"emp".equals(msg.obj.toString())) {
								refs = 1;// 刷新后，当前页重置为1
								overData = (OrderOverData) msg.obj;
								ordernum.setText(overData.getTotal()+"单");
								orderoverlist = overData.getDaylist();
								listAdapter.notifyDataSetChanged();
								pulldownview.notifyDidRefresh(true);
							} else {
								Common.DisplayToast(OrderOverActivity.this,
										"通信失败,请检查网络!", 1);
								pulldownview.notifyDidRefresh(true);
							}
							pulldownview.notifyDidLoadMore(false);
						}
					});
				} else {
					Common.DisplayToast(OrderOverActivity.this, "通信失败,请检查网络!",
							1);
					pulldownview.notifyDidRefresh(true);
					pulldownview.notifyDidLoadMore(false);
				}
			}

			@Override
			public void onLoadMore() {
				// TODO Auto-generated method stub
				// new ForumPostAsyncTask().execute("onLoadMore");
				getNewString(new Handler() {
					@Override
					public void handleMessage(Message msg) {
						if (!"emp".equals(msg.obj.toString())) {

							ArrayList<OrderoverDay> overlist = refoverData.getDaylist();
							int size = overlist!=null? overlist.size():0;
							for (int i = 0; i < size; i++) {
								orderoverlist.add((OrderoverDay) overlist.get(i));
							}
							listAdapter.notifyDataSetChanged();
							if (size>0) {
								pulldownview.notifyDidLoadMore(false);
							} else {
								pulldownview.notifyDidLoadMore(true);
							}
						} else {
							if (refoverData == null) { // 网络失败
								Common.DisplayToast(OrderOverActivity.this,
										"通信失败,请检查网络!", 1);
							} else {
								listAdapter.notifyDataSetChanged();
								pulldownview.notifyDidLoadMore(true);
							}
						}
					}
				});
			}
		});
		
	}
	
	
	private void initArrays(final Handler handler) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					sp = getSharedPreferences(Const.PREF_NAME,
							Context.MODE_PRIVATE);
					String uid = sp.getString("uid", "");
					OrderOverData datas = JsonProcessHelper
							.jsonProcess_getoverOrd("get_overorder_list", uid,
									"1");
					String status = datas.getStatus();
					if (status != null && status.equals("1")) {
						handler.obtainMessage(0, datas).sendToTarget();
					} else {
						handler.obtainMessage(0, "emp").sendToTarget();
					}
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}

			}
		}).start();
	}
	
	//获取更多新闻列表信息
	private void getNewString(final Handler handler) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(2000);
					refs++;

					sp = getSharedPreferences(Const.PREF_NAME,
							Context.MODE_PRIVATE);
					String uid = sp.getString("uid", "");
					refoverData = JsonProcessHelper.jsonProcess_getoverOrd(
							"get_overorder_list", uid, refs + "");
					if (refoverData != null) {
						handler.obtainMessage(0, refoverData).sendToTarget();
					} else {
						handler.obtainMessage(0, "emp").sendToTarget();
						refs--;
					}
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	
	public class ListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return orderoverlist != null ? orderoverlist.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			if (orderoverlist != null) {// 判断软键盘是否已使用
				ViewHolder holder = null;
				if (convertView == null) {
					convertView = inflater.inflate(R.layout.order_over_day,
							null);
					holder = new ViewHolder();
					holder.todate = (TextView) convertView
							.findViewById(R.id.todate); // 
					holder.ordlist = (MyListView) convertView
							.findViewById(R.id.ordlist);
					holder.countwc = (TextView) convertView
							.findViewById(R.id.countwc); // 
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				if (convertView != null && orderoverlist.size() > position) {
					final OrderoverDay overday = orderoverlist.get(position);
					holder.todate.setText(overday.getDate());
					
					String str = "完成"+overday.getCount()+"单";
					SpannableStringBuilder style=new SpannableStringBuilder(str);
					int fstart = str.indexOf("成")+1;
					int fend = str.indexOf("单");
					style.setSpan(new ForegroundColorSpan(Color.RED), fstart,
							fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
					holder.countwc.setText(style);
					
					// 将包含listview的总订单
					holder.ordlist.setAdapter(new OrderoverAdapter(
							OrderOverActivity.this, overday.getOrderlist()));
				}

			}
			return convertView;
		}
	}

	static class ViewHolder {
		private TextView todate = null; // 日期
		private TextView countwc = null; // 完成单
		private MyListView ordlist = null; // 订单列表
		
	}

}
